package hr.ctg.web.resource;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.cache.CacheProvider;
import org.jboss.seam.international.LocaleSelector;
import org.jboss.seam.log.Log;
import org.jboss.seam.servlet.ContextualHttpServletRequest;
import org.jboss.seam.web.AbstractResource;

@Scope(ScopeType.APPLICATION)
@Name("newsResource")
@BypassInterceptors
public class NewsResource extends AbstractResource {
	@Logger
	Log log;

	@Override
	public void getResource(final HttpServletRequest req,
			final HttpServletResponse res) throws ServletException, IOException {
		new ContextualHttpServletRequest(req) {
			@Override
			public void process() throws IOException {
				res.setContentType("text/xml");
				res.setCharacterEncoding("UTF8");
				final CacheProvider cacheProvider = (CacheProvider) Component
						.getInstance("org.jboss.seam.cache.cacheProvider");
				final LocaleSelector ls = (LocaleSelector) Component
						.getInstance(LocaleSelector.class);
				String newsCashKey = "news_"+ls.getLocaleString();
				String news = (String) cacheProvider.get(newsCashKey, "home");
				if (news == null) {
					String languageId = ls.getLocaleString();
					if(languageId.length()<5){
						if("en".equals(languageId)){
							languageId = languageId+"_US";
						}else{
							languageId = languageId+"_"+languageId.toUpperCase();
						}
					}
					final URL ctg = new URL(
							"http://www.crotouristguide.com/portal/c/journal/get_articles?templateId=10501&languageId="
									+ languageId
									+ "&orderByCol=display-date&delta=4");
					final BufferedReader in = new BufferedReader(
							new InputStreamReader(ctg.openStream()));

					String inputLine;
					final StringWriter out = new StringWriter();
					while ((inputLine = in.readLine()) != null)
						out.write(inputLine);
					news = out.toString();
					in.close();
					out.close();

					cacheProvider.put(newsCashKey, "home", news);
				}
				final BufferedWriter out = new BufferedWriter(
						new OutputStreamWriter(res.getOutputStream()));
				out.write(news);
				out.close();
			}
		}.run();

	}

	@Override
	public String getResourcePath() {
		return "/news";
	}

}
